
package org.zjx.app.service;

import com.alibaba.fastjson2.JSON;
import lombok.SneakyThrows;
import org.zjx.app.action.gather.GatherPropAction;
import org.zjx.app.action.gather.GatherRoleAction;
import org.zjx.command.state.AccountState;
import org.zjx.command.state.ItemState;
import org.zjx.command.state.RoleState;
import org.zjx.window.action.Action;
import org.zjx.window.window.IWindow;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class RoleServiceAction extends Action {
    private static final String filePath = "role_state.json";

    public RoleServiceAction(IWindow targetWindow) {
        super(targetWindow);
    }

    @Override
    protected void doExecute() throws Exception {
        RoleState roleState = stateManager.getState(RoleState.class);
        AccountState accountState = stateManager.getState(AccountState.class);
        String playerFilePath =  accountState.getPlayerId() + "-"+filePath;
        if (roleState == null) {
            roleState = getFilePath(new File(playerFilePath));
            if (roleState == null) {
                targetWindow.submitAction(new GatherRoleAction(targetWindow));
                return;
            }
        }
        saveData(playerFilePath,roleState);
        stateManager.registerState(roleState);
        stateManager.getGameState().setGatherRole(true);
    }

    @SneakyThrows
    public void saveData(String playerFilePath,RoleState roleState) {
        String json = JSON.toJSONString(roleState);
        Files.write(Paths.get(playerFilePath), json.getBytes(StandardCharsets.UTF_8));
    }

    @SneakyThrows
    public RoleState getFilePath(File file) {
        if (!file.exists()) return null;
        String json = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
        if (json.isEmpty()) return null;
        return JSON.parseObject(json, RoleState.class);
    }

}
